package cc.md888.app.application.activatecode;

import cc.md888.app.exception.BizRuntimeException;
import cc.md888.app.model.activatecode.SendEmailActivateCodeCmd;
import cc.md888.result.ResultCode;
import jakarta.mail.NoSuchProviderException;
import jakarta.mail.Session;
import jakarta.mail.Transport;
import jakarta.mail.internet.InternetAddress;
import jakarta.mail.internet.MimeMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Properties;

@Slf4j
@Component
public class ActivateEmailService {

    private String sender = "noreply@md888.cc";

    private String password = "zfyZhYekfcK2UHkG";

    private Session session;


    public void send(SendEmailActivateCodeCmd cmd){

        try {
            initSession();
            MimeMessage message = createMimeMessage(session, sender, cmd.getEmail(),  cmd.getCode());
            Transport transport = session.getTransport();
            transport.connect(sender, password);
            transport.sendMessage(message, message.getAllRecipients());
            transport.close();
        } catch (Exception e) {
            log.error("发送激活邮件失败", e);
            throw BizRuntimeException.from(ResultCode.ERROR, "发送激活邮件失败");
        }
    }


    private synchronized void initSession(){
        if(session != null){
            return;
        }

        Properties mailProps = getMailServer();
        session = Session.getInstance(mailProps);
    }


    /**
     * 创建一封只包含文本的简单邮件
     *
     * @param session     和服务器交互的会话
     * @param sendMail    发件人邮箱
     * @param receiveMail 收件人邮箱
     * @return
     * @throws Exception
     */
    public static MimeMessage createMimeMessage(Session session, String sendMail, String receiveMail, String activateCode) throws Exception {
        // 1. 创建一封邮件
        MimeMessage message = new MimeMessage(session);

        // 2. From: 发件人
        message.setFrom(new InternetAddress(sendMail, "", "UTF-8"));

        // 3. To: 收件人（可以增加多个收件人、抄送、密送）
        message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(receiveMail, "", "UTF-8"));

        // 4. Subject: 邮件主题
        message.setSubject("你的激活码", "UTF-8");

        // 5. Content: 邮件正文（可以使用html标签）
        message.setContent("您的激活码：" + activateCode , "text/html;charset=UTF-8");
        // 6. 设置发件时间
        message.setSentDate(new Date());

        // 7. 保存设置
        message.saveChanges();

        return message;
    }


    public Properties getMailServer() {
        Properties properties = new Properties();
        properties.put("mail.debug", "false");
        properties.put("mail.debug.auth", "false");
        properties.put("mail.store.protocol", "smtp");
        properties.put("mail.smtp.host", "smtp.larksuite.com");
        properties.put("mail.smtp.port", "465");
        properties.put("mail.smtp.ssl.enable", "true");
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.auth.mechanisms", "login");
        return properties;
    }


    public static void main(String[] args) {
        ActivateEmailService activateEmailService = new ActivateEmailService();
        SendEmailActivateCodeCmd cmd = new SendEmailActivateCodeCmd();
        cmd.setEmail("xyjwfn@gmail.com");
        cmd.setCode("123456");
        activateEmailService.send(cmd);
    }
}
